from .grid import GridRenderer
from .player import PlayerAreaRenderer
from .status import StatusBarRenderer
import pygame

from const import (
    YELLOW, BLACK, WHITE,
    SCREEN_WIDTH, SCREEN_HEIGHT,
    PLAYER_PANEL_WIDTH,
)

from model import Model


class FontManager:
    def __init__(self):
        self._font_cache = {}


    def get_font(self, size, bold=False, italic=False) -> pygame.font.Font:
        key = (size, bold, italic)
        if key not in self._font_cache:
            self._font_cache[key] = self.setup_fonts(size, bold, italic)
        return self._font_cache[key]

    def setup_fonts(self, font_size, bold=False, italic=False):
        font_preferences = ['Bangers', 'Iosevka Regular', 'Comic Sans', 'Courier New']
        available = pygame.font.get_fonts()
        prefs = [x.lower().replace(' ', '') for x in font_preferences]
        for pref in prefs:
            a = [x for x in available if x.startswith(pref)]
            if a:
                return pygame.font.SysFont(','.join(a), font_size, bold, italic)
        return pygame.font.SysFont(None, font_size, bold, italic)


class Renderer:

    screen: pygame.Surface
    font_mgr: FontManager

    def __init__(self, screen):
        self.screen = screen
        self.font_mgr = FontManager()
        
        # 初始化各组件时注入字体管理器
        self.status_renderer = StatusBarRenderer(screen, self.font_mgr)
        self.player_renderer = PlayerAreaRenderer(screen, self.font_mgr)
        self.grid_renderer = GridRenderer(screen, self.font_mgr)

    def handle_mouse_hover(self, mouse_pos: tuple[int, int], model: Model):
        """
        处理鼠标悬停事件
        """
        self.status_renderer.handle_mouse_hover(mouse_pos)
        self.player_renderer.handle_mouse_hover(mouse_pos)
        self.grid_renderer.handle_mouse_hover(mouse_pos, model.grid_manager)

    def handle_click(self, mouse_pos: tuple[int, int], model: Model) -> bool:
        """
        处理玩家区域的点击事件

        Args:
            mouse_pos: 鼠标点击位置坐标

        Returns:
            bool: 如果点击在玩家区域内返回True，否则返回False
        """

        if self.player_renderer.handle_click(mouse_pos):
            return True


        if self.status_renderer.handle_click(mouse_pos, model.player_manager):
            return True

        if self.grid_renderer.handle_click(mouse_pos, model):
            return True

        return False


    def draw_view(self, model: Model):
        self.grid_renderer.draw_grid(model)
        self.player_renderer.draw_players(model.player_manager)
        self.status_renderer.draw_status_bar(model)
    
    def draw_event_message(self, message):
        if message:
            self.status_renderer.render_event_message(message)
    
    def draw_game_over(self, winner):
        font = self.font_mgr.get_font(36)
        small_font = self.font_mgr.get_font(12)

        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        self.screen.blit(overlay, (0, 0))
        message = f"player {winner} win！"
        game_over_text = font.render(message, True, WHITE)
        text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
        self.screen.blit(game_over_text, text_rect)
        restart_text = small_font.render("press R to restart game", True, WHITE)
        restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 40))
        self.screen.blit(restart_text, restart_rect)